<template>
  <view class="my-orders-page">
    <!-- 顶部导航栏 -->
    <uni-nav-bar 
      :border="false"
      background-color="#ffffff"
      color="#333333"
      title="我的接单"
      left-icon="left"
      @clickLeft="goBack"
    >
      <template #right>
        <view class="nav-right">
          <view class="refresh-btn" @click="refreshOrders">
            <text class="refresh-icon">🔄</text>
            <text class="refresh-text">刷新</text>
          </view>
          <view class="history-btn" @click="goToHistory">
            <text class="history-icon">📋</text>
            <text class="history-text">历史</text>
          </view>
        </view>
      </template>
    </uni-nav-bar>

    <!-- 订单状态切换 -->
    <view class="status-tabs">
      <view 
        class="tab-item"
        :class="{ active: activeStatus === 'all' }"
        @click="switchStatus('all')"
      >
        全部
        <view class="badge" v-if="getTotalCount() > 0">{{ getTotalCount() }}</view>
      </view>
      <view 
        class="tab-item"
        :class="{ active: activeStatus === 'ongoing' }"
        @click="switchStatus('ongoing')"
      >
        进行中
        <view class="badge" v-if="getOngoingCount() > 0">{{ getOngoingCount() }}</view>
      </view>
      <view 
        class="tab-item"
        :class="{ active: activeStatus === 'completed' }"
        @click="switchStatus('completed')"
      >
        已完成
        <view class="badge" v-if="getCompletedCount() > 0">{{ getCompletedCount() }}</view>
      </view>
    </view>

    <!-- 订单列表 -->
    <view class="orders-container">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-state">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 订单列表 -->
      <view 
        v-for="order in filteredMyOrders"
        :key="order.id"
        class="my-order-card"
        @click="viewOrderDetail(order.id)"
      >
        <view class="order-header">
          <text class="order-title">{{ order.title }}</text>
          <text class="order-status" :class="order.status">{{ getStatusText(order.status) }}</text>
        </view>

        <view class="order-info">
          <view class="time-info">
            <text class="label">接单时间:</text>
            <text class="value">{{ order.acceptTime }}</text>
          </view>
          
          <view class="location-info">
            <view class="location-item">
              <view class="location-dot blue"></view>
              <text class="location-text">{{ order.pickup }}</text>
            </view>
            <view class="location-item">
              <view class="location-dot red"></view>
              <text class="location-text">{{ order.delivery }}</text>
            </view>
          </view>

          <view class="order-footer">
            <text class="price">¥ {{ order.price }}</text>
            <view class="order-actions" v-if="order.status === 'ongoing'">
              <button class="action-btn complete-btn" @click.stop="completeOrder(order.id)">
                完成订单
              </button>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="!loading && filteredMyOrders.length === 0">
        <view class="empty-icon">
          <text class="empty-emoji">📋</text>
        </view>
        <text class="empty-text">{{ getEmptyText() }}</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { requestUrl } from '@/config'

// 声明uni全局变量
declare const uni: any

// 订单状态类型
type OrderStatus = 'ongoing' | 'completed'

// 我的订单数据类型
interface MyOrder {
  id: number
  title: string
  pickup: string
  delivery: string
  price: string
  status: OrderStatus
  acceptTime: string
  completeTime?: string
}

// 响应式数据
const activeStatus = ref<'all' | OrderStatus>('all')
const myOrders = ref<MyOrder[]>([])
const loading = ref(false)

// 计算属性：过滤后的订单
const filteredMyOrders = computed(() => {
  if (activeStatus.value === 'all') {
    return myOrders.value
  }
  return myOrders.value.filter(order => order.status === activeStatus.value)
})

// 页面加载时获取我的订单数据
onMounted(() => {
  loadMyOrders()
})

// 页面显示时刷新数据
const onShow = () => {
  loadMyOrders()
}

// 加载我的订单数据（使用 Axios + config.ts）
const loadMyOrders = async () => {
  loading.value = true
  try {
    const userId = uni.getStorageSync('userId')
    if (!userId) {
      // 如果没有用户ID，直接加载本地存储的数据
      loadFromLocalStorage()
      return
    }
    
    // 使用 Axios 和 config.ts 中的 requestUrl
    const response = await axios.get(`${requestUrl}/jjk/myOrders/user/${userId}`, {
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.data.success) {
      // 转换数据格式以匹配前端需求
      myOrders.value = response.data.data.map((order: any) => ({
        id: order.orderId,
        title: order.title,
        pickup: order.pickup,
        delivery: order.delivery,
        price: order.price,
        status: order.status,
        acceptTime: new Date(order.acceptTime).toLocaleString(),
        completeTime: order.completeTime ? new Date(order.completeTime).toLocaleString() : undefined
      }))
      
      console.log('从后端API加载订单成功:', myOrders.value)
      
      if (myOrders.value.length > 0) {
        uni.showToast({
          title: `共${myOrders.value.length}个订单`,
          icon: 'none'
        })
      }
    } else {
      console.log('后端API返回失败，使用本地存储数据')
      // fallback到本地存储
      loadFromLocalStorage()
    }
  } catch (error) {
    console.error('加载订单失败:', error)
    // fallback到本地存储
    loadFromLocalStorage()
    uni.showToast({
      title: '网络错误，使用本地数据',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 本地存储备用方案
const loadFromLocalStorage = () => {
  const storedOrders = uni.getStorageSync('myOrders')
  if (storedOrders) {
    myOrders.value = JSON.parse(storedOrders)
  }
}

// 刷新订单数据
const refreshOrders = () => {
  uni.showLoading({ title: '刷新中...' })
  loadMyOrders().then(() => {
    uni.hideLoading()
  }).catch(() => {
    uni.hideLoading()
  })
}

// 获取状态文本
const getStatusText = (status: OrderStatus): string => {
  const statusMap = {
    'ongoing': '进行中',
    'completed': '已完成'
  }
  return statusMap[status]
}

// 获取不同状态订单数量
const getTotalCount = (): number => myOrders.value.length
const getOngoingCount = (): number => myOrders.value.filter(order => order.status === 'ongoing').length
const getCompletedCount = (): number => myOrders.value.filter(order => order.status === 'completed').length

// 获取空状态提示文本
const getEmptyText = (): string => {
  const textMap = {
    'all': '还没有接单记录',
    'ongoing': '暂无进行中的订单',
    'completed': '暂无已完成的订单'
  }
  return textMap[activeStatus.value]
}

// 方法
const goBack = () => {
  uni.navigateBack()
}

const goToHistory = () => {
  uni.navigateTo({
    url: '/pages/JJK/history-orders'
  })
}

const switchStatus = (status: 'all' | OrderStatus) => {
  activeStatus.value = status
}

const viewOrderDetail = (orderId: number) => {
  uni.navigateTo({
    url: `/pages/JJK/order-detail?id=${orderId}`
  })
}

const completeOrder = (orderId: number) => {
  uni.showModal({
    title: '确认完成',
    content: '确定要完成这个订单吗？',
    success: async (res: any) => {
      if (res.confirm) {
        try {
          const userId = uni.getStorageSync('userId')
          
          // 使用 Axios 和 config.ts 中的 requestUrl
          const response = await axios.put(`${requestUrl}/jjk/myOrders/complete/${orderId}`, 
            { userId: userId },
            {
              timeout: 10000,
              headers: {
                'Content-Type': 'application/json'
              }
            }
          )
          
          if (response.data.success) {
            // 更新本地数据
            const orderIndex = myOrders.value.findIndex(order => order.id === orderId)
            if (orderIndex !== -1) {
              myOrders.value[orderIndex].status = 'completed'
              myOrders.value[orderIndex].completeTime = new Date().toLocaleString()
            }
            
            uni.showToast({
              title: '订单已完成',
              icon: 'success'
            })
          } else {
            uni.showToast({
              title: response.data.message || '完成订单失败',
              icon: 'error'
            })
          }
        } catch (error) {
          console.error('完成订单失败:', error)
          // fallback到本地更新
          const orderIndex = myOrders.value.findIndex(order => order.id === orderId)
          if (orderIndex !== -1) {
            myOrders.value[orderIndex].status = 'completed'
            myOrders.value[orderIndex].completeTime = new Date().toLocaleString()
            
            // 保存到本地存储
            uni.setStorageSync('myOrders', JSON.stringify(myOrders.value))
            
            uni.showToast({
              title: '订单已完成',
              icon: 'success'
            })
          } else {
            uni.showToast({
              title: '操作失败，请重试',
              icon: 'error'
            })
          }
        }
      }
    }
  })
}

// 暴露给外部使用的方法（供其他页面调用）
const addMyOrder = (order: any) => {
  const newOrder: MyOrder = {
    id: order.id,
    title: order.title,
    pickup: order.pickup,
    delivery: order.delivery,
    price: order.price,
    status: 'ongoing',
    acceptTime: new Date().toLocaleString()
  }
  
  myOrders.value.unshift(newOrder)
  
  // 保存到本地存储
  uni.setStorageSync('myOrders', JSON.stringify(myOrders.value))
}

// 下拉刷新
const onRefresh = () => {
  loadMyOrders()
}

// 导出方法供外部使用
defineExpose({
  addMyOrder,
  onRefresh
})
</script>

<style lang="scss" scoped>
.my-orders-page {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 16px;
  
  .refresh-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 8px 12px;
    background-color: #dbeafe;
    border-radius: 20px;
    cursor: pointer;
    
    .refresh-icon {
      font-size: 16px;
    }
    
    .refresh-text {
      font-size: 12px;
      color: #2563eb;
      font-weight: 500;
    }
  }
  
  .history-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 8px 12px;
    background-color: #f3f4f6;
    border-radius: 20px;
    cursor: pointer;
    
    .history-icon {
      font-size: 16px;
    }
    
    .history-text {
      font-size: 12px;
      color: #6b7280;
      font-weight: 500;
    }
  }
}

.status-tabs {
  display: flex;
  background-color: #fff;
  padding: 10px 20px;
  
  .tab-item {
    flex: 1;
    text-align: center;
    padding: 8px 16px;
    border-radius: 20px;
    position: relative;
    color: #666;
    
    &.active {
      background-color: #ff6b4a;
      color: #fff;
    }
    
    .badge {
      position: absolute;
      top: -5px;
      right: 10px;
      background-color: #ff4444;
      color: #fff;
      border-radius: 50%;
      width: 18px;
      height: 18px;
      font-size: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.orders-container {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  
  .loading-spinner {
    width: 30px;
    height: 30px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #ff6b4a;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 16px;
  }
  
  .loading-text {
    font-size: 14px;
    color: #666;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.my-order-card {
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 10px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  
  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    
    .order-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }
    
    .order-status {
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      
      &.ongoing {
        background-color: #e3f2fd;
        color: #1976d2;
      }
      
      &.completed {
        background-color: #e8f5e8;
        color: #388e3c;
      }
    }
  }
  
  .order-info {
    .time-info {
      display: flex;
      margin-bottom: 8px;
      
      .label {
        font-size: 14px;
        color: #666;
        margin-right: 8px;
        min-width: 70px;
      }
      
      .value {
        font-size: 14px;
        color: #333;
      }
    }
    
    .location-info {
      margin-bottom: 12px;
      
      .location-item {
        display: flex;
        align-items: center;
        margin-bottom: 6px;
        
        .location-dot {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          margin-right: 8px;
          
          &.blue {
            background-color: #2196f3;
          }
          
          &.red {
            background-color: #f44336;
          }
        }
        
        .location-text {
          flex: 1;
          font-size: 14px;
          color: #666;
        }
      }
    }
    
    .order-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .price {
        font-size: 18px;
        font-weight: bold;
        color: #f44336;
      }
      
      .order-actions {
        .action-btn {
          border: none;
          border-radius: 20px;
          padding: 6px 16px;
          font-size: 14px;
          
          &.complete-btn {
            background-color: #4caf50;
            color: #fff;
          }
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  
  .empty-icon {
    width: 120px;
    height: 120px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .empty-emoji {
      font-size: 60px;
      opacity: 0.6;
    }
  }
  
  .empty-text {
    font-size: 16px;
    color: #999;
  }
}
</style>
